<template>
  <div>
    <!-- 返利池查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhRebatePoolQuery"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onSyncTableData="syncDataHandle"
        :mergeCellMethod="objectSpanMethod"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="exportHandler">导 出</multiuse-button>
          <!-- <multiuse-button size="small" type="primary" :click="exportFrostAmountHandler">导出冻结明细</multiuse-button> -->
        </template>
      </FilterTable>
    </Spin>

    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="isPool" :title="'返利池查询'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <DetailPool :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>

    <BaseDialog :visible.sync="isAmount" :title="'余额锁定明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <DetailAmount :rowData="formData" @close="emitCloseHandler2" />
    </BaseDialog>
    <BaseDialog :visible.sync="isFrostAmount" :title="'冻结明细查询'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <FreezeDetail :rowData="formData" @close="emitCloseHandler3" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getRegion } from '@/api/omFinance';
import { queryList, exportExcel,exportFrostAmountExcel,exporturl } from '@/api/omFinance/RebateManage/RebatePoolQuery';
import { exportExcelFile } from '@/utils/index';
import DetailPool from './DetailPool';
import DetailAmount from './DetailAmount';
import OwnerSearch from '../OwnerSearch';
import FreezeDetail from './FreezeDetail';

export default {
  name: 'RebatePoolQuery',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      isDealer: false,
      isPool: false,
      isAmount: false,
      isFrostAmount: false,
      exportLoading: false,
      handleType: '',
      drawerTitle: '',
      spanArr1: [], // 一个空的数组，用于存放每一行记录的合并数
      pos1: 0 // spanArr 的索引
    };
  },
  components: {
    DetailPool,
    DetailAmount,
    OwnerSearch,
    FreezeDetail
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getDeptData();
  },
  methods: {
    // 合并
    syncDataHandle(dataList) {
      if (!dataList.length) return;
      // 设定一个数组spanArr/contentSpanArr来存放要合并的格数，同时还要设定一个变量pos/position来记录
      this.spanArr1 = [];
      for (let i = 0; i < dataList.length; i++) {
        if (i === 0) {
          this.spanArr1.push(1);
          this.pos1 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1列)
          if (dataList[i].ownerCode === dataList[i - 1].ownerCode) {
            this.spanArr1[this.pos1] += 1;
            this.spanArr1.push(0);
          } else {
            this.spanArr1.push(1);
            this.pos1 = i;
          }
          console.log(JSON.stringify(this.spanArr1), this.pos1);
        }
      }
    },
    // 处理合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    frostAmountHandle(row) {
      this.isFrostAmount = true;
      this.formData = row;
    },
    overHandle(row) {
      this.isAmount = true;
      this.formData = row;
    },
    detailHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    showHandler() {
      this.drawerTitle = `${this.conf[this.handleType]}`;
      this.isPool = true;
    },
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        res.data.map(x => {
          this.topFilterList.find(item => item.fieldName == 'deptId').itemList.push({ text: x.orgName, value: x.id });
        });
      }
    },
    // 导出
    async exportHandler() {
        let json = Object.assign({}, { CODE: 'CODE_0000099' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;
      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '返利池查询');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    // 导出全部冻结明细
    async exportFrostAmountHandler() {
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          exportFrostAmountExcel({})
            .then(response => {
              exportExcelFile(response.data, '全部冻结明细');
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.dealerCode = dealerCodes.toString();
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
    },
    emitCloseHandler1(val) {
      this.isPool = val;
    },
    emitCloseHandler2(val) {
      this.isAmount = val;
    },
    emitCloseHandler3(val) {
      this.isFrostAmount = val;
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '是否有余额',
          fieldName: 'isAmount',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '请选择',
          itemList: this.createDictList('6008')
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'ownerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利账户类型',
          dataIndex: 'rebateTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '累计入账',
          dataIndex: 'totalInAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '累计出账',
          dataIndex: 'totalOutAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '返利余额',
          dataIndex: 'balanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '预扣金额',
          dataIndex: 'frozenAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true,
          render: props => {
            return (
              <el-link type="warning" underline={true} onClick={() => this.overHandle(props.row)}>
                {props.row.frozenAmount}
              </el-link>
            );
          }
        },
        {
          title: '冻结金额',
          dataIndex: 'frostAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true,
          // render: props => {
          //   return (
          //     <el-link type="warning" underline={true} onClick={() => this.frostAmountHandle(props.row)}>
          //       {props.row.frostAmount}
          //     </el-link>
          //   );
          // }
        },
        {
          title: '过期金额',
          dataIndex: 'overdueAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '账户状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '1003')}</span>;
          }
        },
        {
          title: '最后更新日期',
          dataIndex: 'updatedAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    }
  }
};
</script>
